/*
 * app_main.c
 *
 *  Created on: Jan 28, 2022
 *      Author: Rupert
 */

#include "app_main.h"

#include "stm32h7xx_hal.h"
#include "stm32h7xx_ll_tim.h"
#include "cmsis_os.h"

#include "utils_log.h"
#include "status.h"
#include "rate2clk.h"

extern ADC_HandleTypeDef hadc1;
static uint16_t curr_storage = 0;

static inline void StartSample(void)
{
	LL_TIM_EnableCounter(TIM3);
	HAL_ADC_Start_DMA(
			&hadc1,
			(uint32_t *)status_params.adc_data,
			curr_storage
	);
}
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
{
	static uint32_t last_sample_rate = 10000;
	static TimerCfgParamStructure* cfg = NULL;
	HAL_ADC_Stop_DMA(hadc);
	LL_TIM_DisableCounter(TIM3);
	status_params.sample_cplt_flag = 1;
	// 更新采样参数
	if(last_sample_rate != status_params.sample_rate)
	{
		cfg = rate2clk(status_params.sample_rate);
		last_sample_rate = status_params.sample_rate;
		LL_TIM_SetPrescaler(TIM3, cfg->Prescaler);
		LL_TIM_SetAutoReload(TIM3, cfg->AutoReload);
	}
	if(curr_storage != status_params.storage_depth)
	{
		curr_storage = status_params.storage_depth;
	}
}

void AppMain(void *argument)
{
	// 初始化存储深度
	  curr_storage = status_params.storage_depth;
	  StartSample();
	  uint16_t* data;
	  /* Infinite loop */
	  while(1)
	  {
		  if(status_params.sample_cplt_flag)
		  {
			  data = status_params.adc_data;
			  SwitchADCDataBuffer();
			  StartSample();
			  status_params.sample_cplt_flag = 0;
			  for(uint16_t i = 0; i < curr_storage; i++)
			  {
				  Utils_LogPrintf("%f\n", data[i] / 65536.0 * 3.3);
			  }
		  }
//		  Utils_LogPrintf("Prescaler: %ld\tAutoReload: %ld\n", LL_TIM_GetPrescaler(TIM3), LL_TIM_GetAutoReload(TIM3));
//		  Utils_LogPrintf("Rate: %ld,\tDepth: %ld\n", status_params.sample_rate, status_params.storage_depth);
	    osDelay(1);
	  }
}
